#!/bin/bash

# Quick Docker MySQL Startup Script
# Usage: ./quick-docker-mysql.sh [start|stop|status|connect]

set -e

# Configuration
CONTAINER_NAME="property-mysql"
ROOT_PASSWORD="root123"
DB_NAME="property_cleaning"
DB_USER="property_user"
DB_PASSWORD="property_pass"
PORT="3306"

case "${1:-start}" in
    start)
        echo "Starting MySQL in Docker..."
        
        # Stop existing container
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        docker rm "$CONTAINER_NAME" 2>/dev/null || true
        
        # Start new container
        docker run -d \
            --name "$CONTAINER_NAME" \
            -p "$PORT:3306" \
            -e MYSQL_ROOT_PASSWORD="$ROOT_PASSWORD" \
            -e MYSQL_DATABASE="$DB_NAME" \
            -e MYSQL_USER="$DB_USER" \
            -e MYSQL_PASSWORD="$DB_PASSWORD" \
            mysql:8.0
        
        echo "Waiting for MySQL to be ready..."
        sleep 10
        
        # Test connection
        docker exec "$CONTAINER_NAME" mysql -u"$DB_USER" -p"$DB_PASSWORD" -e "SELECT 'MySQL is ready!' as status;" "$DB_NAME"
        
        echo "MySQL started successfully!"
        echo "Connection string: mysql -h127.0.0.1 -P$PORT -u$DB_USER -p$DB_PASSWORD $DB_NAME"
        ;;
        
    stop)
        echo "Stopping MySQL container..."
        docker stop "$CONTAINER_NAME" 2>/dev/null || true
        echo "MySQL stopped"
        ;;
        
    status)
        if docker ps | grep -q "$CONTAINER_NAME"; then
            echo "MySQL is running"
            docker ps --filter "name=$CONTAINER_NAME"
        else
            echo "MySQL is not running"
        fi
        ;;
        
    connect)
        echo "Connecting to MySQL..."
        docker exec -it "$CONTAINER_NAME" mysql -u"$DB_USER" -p"$DB_PASSWORD" "$DB_NAME"
        ;;
        
    *)
        echo "Usage: $0 [start|stop|status|connect]"
        echo ""
        echo "Options:"
        echo "  start   - Start MySQL container"
        echo "  stop    - Stop MySQL container"
        echo "  status  - Check MySQL status"
        echo "  connect - Connect to MySQL"
        ;;
esac